package com.qmyx.supply.admin.shiro;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import com.ytjj.qmyx.supplychain.common.api.CommonResult;
import com.ytjj.qmyx.supplychain.common.api.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 权限验证异常信息
 */
@ControllerAdvice
@Slf4j
public class AuthExceptionHandler implements HandlerExceptionResolver {

    @ExceptionHandler
    @ResponseBody
    public CommonResult ErrorHandler(AuthorizationException e) {
        log.error("没有通过权限验证！", e);
        return CommonResult.failed(ResultCode.FORBIDDEN);
    }

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        e.printStackTrace();
        ModelAndView mv = new ModelAndView();
        FastJsonJsonView view = new FastJsonJsonView();
        Map<String, Object> attributes = new HashMap<String, Object>();
        if (e instanceof UnauthenticatedException) {
            attributes.put("sucess", "false");
            attributes.put("info", "token错误");
        } else if (e instanceof UnauthorizedException) {
            attributes.put("sucess", "false");
            attributes.put("info", "用户无权限");
        } else {
            attributes.put("sucess", "false");
            attributes.put("info", e.getMessage());
            log.error("发生未处理的异常={}",e.getMessage(),e);
        }
        view.setAttributesMap(attributes);
        mv.setView(view);
        return mv;
    }
}
